package edu.gatech.ece6102;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * User: deepal
 * Date: Oct 5, 2010
 * Time: 1:23:59 PM
 */
public class Relay extends Thread {
    final static int BUFSIZ = 2048;
    InputStream in;
    OutputStream out;
    byte buf[] = new byte[BUFSIZ];
    OutputStream os;
    String enc = "8859_1";
    boolean write = false;

    Relay(InputStream in, OutputStream out, OutputStream os, String enc, boolean value) {
        this.in = in;
        this.out = out;
        this.os = os;
        this.enc = enc;
        this.write = value;
    }

    public String getEncoding() {
        return enc;
    }

    public void readClient() {
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        try {
            int n = in.read(buf);
            bout.write(buf, 0, n);
            bout.flush();
            if (os != null) {
//                os.write(buf, 0, n);
//                os.flush();
            }
        out.write(bout.toByteArray());
        out.flush();
        } catch (IOException e) {
        } finally {
            try {
             //   in.close();
                bout.close();
            } catch (IOException e) {
            }
        }
    }

    public void run() {
        int n;
        try {
            System.out.println("came here" + this);
            while ((n = in.read(buf)) > 0) {
                System.out.println(n);
                out.write(buf, 0, n);
                out.flush();
                if (os != null) {
//                    os.write(buf, 0, n);
//                    os.flush();
                }
            }
        } catch (IOException e) {
        } finally {
            try {
                System.out.println("closer ");
                in.close();
                out.close();
            } catch (IOException e) {
            }
        }
        System.out.println("done");
    }


    public void setEncoding(String enc) {
        this.enc = enc;
    }
}

